require("../../assets/css/normalize.css");
require("../../assets/css/reset.css");
require("../../assets/fonts/iconfont.css");

require("./sports_rideing.less");
const dom = require("../../utils/dom.js");
const axios = require("axios");
const date = require("../../utils/date.js");
document.addEventListener("DOMContentLoaded", function () {
	let duration = 0; //持续时间
	let meter = 0; //总里程
	let calorie = 0; //卡路里
	let timer = null; //定时器标识
	function start() {
		timer = setInterval(function () {
			//速度
			let speed = getRand(7, 9);
			dom.get("#velocity").textContent = speed + "米/秒";

			//时间
			duration++;
			dom.get("#time").textContent = date.getHMS(duration);

			//里程
			meter += speed;
			dom.get("#distancenum").textContent = (meter / 1000).toFixed(3);

			//卡路里
			calorie = 60 * (meter / 1000) * 1.036;
			dom.get("#calorie").textContent = calorie.toFixed(2);
		}, 100);
	}
	start();
	//获取两个整数之间的随机数
	function getRand(min, max) {
		return Math.floor(Math.random() * (max - min + 1)) + min;
	}
	// 暂停
	dom.get(".pause").addEventListener("click", function () {
		dom.get(".pause").style.display = "none";
		dom.get(".play").style.display = "block";
		dom.get(".end").style.display = "block";
		clearInterval(timer); //清除定时器标识，停止计时
	});

	// 继续
	dom.get(".play").addEventListener("click", function () {
		dom.get(".pause").style.display = "block";
		dom.get(".play").style.display = "none";
		dom.get(".end").style.display = "none";
		start(); //继续执行定时器
	});
	let token = localStorage.getItem("token");
	axios.defaults.headers.common["Authorization"] = "Bearer " + token;
	dom.get(".end").addEventListener("click", function () {
		axios
			.post("http://fitness.h5.itsource.cn:3701/api/exercise/save", {
				type: 1,
				duration,
				calorie,
				meter,
			})
			.then((res) => {
				if (res.data.errno === 0) {
					location.href = "sports_ride.html";
				}
			});
	});
});
